﻿using Godot;
using NLua;
using System;
using System.Collections.Generic;

public class ModLoader
{
    private static ModLoader Instance;
    private ModLoader()
    {
    }
    public static ModLoader GetInstance()
    {
        if (Instance == null)
        {
            Instance = new ModLoader();
        }
        return Instance;
    }

    public List<Lua> ModInstand = new List<Lua>();
    public void AddMod(Lua mod)
    {
        ModInstand.Add(mod);
    }
    public void CallAll(String method, params object[] args)
    {
        for (int i = 0; i < ModInstand.Count; i++)
        {
            ModInstand[i].GetFunction(method).Call(args);
        }
    }
    public void Run()
    {
        GD.Print("[ModLoader] √");
        LoadModes();
    }
    public void LoadModes()
    {
        Directory dir = new Directory();
        if (dir.Open("mods") != Error.Ok)
        {
            dir.MakeDir("mods");
        }
        dir.ListDirBegin(true);
        String filename = dir.GetNext();
        while (filename != "")
        {
            if (!dir.CurrentIsDir())
            {
                Lua lua = new Lua();
                lua["ModLoader"] = this;
                lua.RegisterFunction("RegisterItem",null,typeof(ModLoader).GetMethod("RegisterItem"));
                lua.LoadCLRPackage();
                lua.LoadFile($"mods/{filename}");
            }
            filename = dir.GetNext();
        }
        dir.ListDirEnd();
    }


    public BlockMaterial GetBlockMaterial(String name)
    {
        return new BlockMaterial(name);
    }
    public ItemMateria RegisterItem(String Name, String DisPlayName)
    {
        GD.Print($"[Mod] RegisterItem{Name}");
        return Materials.RegistryItem(new ItemMateria(Name).SetDisplayName(DisPlayName).SetImageSet(new ImageSet()));
    }
}
